package com.it.ems.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.it.ems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import com.it.ems.entity.User;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/users")
@PreAuthorize("hasRole('ADMIN')")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        System.out.println("正在获取用户列表");
        List<User> users = userService.findAll();
        System.out.println("获取到 " + users.size() + " 个用户");
        
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = (User) auth.getPrincipal();
        System.out.println("当前登录用户ID: " + currentUser.getId());
        
        model.addAttribute("users", users);
        model.addAttribute("currentUserId", currentUser.getId());
        return "users";
    }

    @PostMapping("/{userId}/role")
    @ResponseBody
    public ResponseEntity<?> updateUserRole(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        System.out.println("正在处理更新用户角色请求 - 用户ID: " + userId);
        try {
            String newRole = request.get("role");
            System.out.println("新角色: " + newRole);
            
            // 检查是否是当前用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User currentUser = (User) auth.getPrincipal();
            if (userId.equals(currentUser.getId())) {
                System.out.println("不能修改自己的角色");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "不能修改自己的角色");
                return ResponseEntity.badRequest().body(response);
            }
            
            userService.updateUserRole(userId, newRole);
            System.out.println("用户角色更新成功");
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("更新用户角色时发生错误: " + e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{userId}")
    @ResponseBody
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        System.out.println("正在处理删除用户请求 - 用户ID: " + userId);
        try {
            // 检查是否是当前用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User currentUser = (User) auth.getPrincipal();
            if (userId.equals(currentUser.getId())) {
                System.out.println("不能删除自己的账户");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "不能删除自己的账户");
                return ResponseEntity.badRequest().body(response);
            }
            
            userService.deleteUser(userId);
            System.out.println("用户删除成功");
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("删除用户时发生错误: " + e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 